package web;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import utils.JDBCUtils;

public class LoginServlet extends BaseServlet{

    public void loginto(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String userNum = "";
        String userPwd = "";
        String userAbl = "";
        // 登录检测 跳转 成功设置临时时设置 单次Cookies

//        Cookie[] cookies = req.getCookies();
//        for(Cookie cookie:cookies) {
//            System.out.println(cookie.getName() + " " + cookie.getValue());
//        }


        // 修改编码格式
        req.setCharacterEncoding("UTF-8");		// 接受到的
        resp.setContentType("text/html; charset=UTF-8");		// 修改发送的

        userNum = req.getParameter("userNum");
        userPwd = req.getParameter("userPwd");
        System.out.println("进行 登录 校验");

        // 数据库调用相关
        Connection connection = null;
        PreparedStatement pStatement = null;
        ResultSet rsSet = null;

        // 连接数据库
        connection = JDBCUtils.getConnection();
        // 创建sql语句
        String sql = "select userPwd,userAbl from student where userNum = ?";
        // 与上sql问号一一对应


        try {
            pStatement = connection.prepareStatement(sql);
            pStatement.setString(1, userNum );
            rsSet = pStatement.executeQuery();




            if(rsSet.next()) {
                if (rsSet.getString("userPwd").equals(userPwd)) {
                    userAbl = rsSet.getString("userAbl");

                    System.out.println("用户成功登录");

                    // 创建Cookies 对象
                    Cookie cookie = new Cookie("userNum",userNum);
                    Cookie cookie1 = new Cookie("userAbl",userAbl);
                    // 通知客户端保存 Cookies
                    resp.addCookie(cookie);
                    resp.addCookie(cookie1);
                    System.out.println("添加Cookies成功");
                    resp.getWriter().append("用户成功登录");
                    resp.sendRedirect("/webdemo2/userspace");

                } else {
                    resp.getWriter().append("false");
                    System.out.println("用户登录失败");
                }
            } else {
                resp.getWriter().append("false");
                System.out.println("用户名不存在失败");
            }
            // 然后将这个用户发给前端
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JDBCUtils.close(connection, pStatement,rsSet);	// 关闭连接
        }
    }
}
